package com.easyban.filter;

import cn.hutool.core.util.ReUtil;
import cn.hutool.json.JSONUtil;
import com.easyban.common.BaseContext;
import com.easyban.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.annotation.Order;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 检查用户是否已经登录
 */
@Slf4j
@Order(1)
@WebFilter(filterName = "LoginCheckFilter", urlPatterns = "/*")
public class LoginCheckFilter implements Filter {
    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //获取本次请求的URI
        String requestURI = request.getRequestURI();
        log.info("拦截到请求：{}", request.getRequestURI());

        //定义不需要处理的请求路径
        String[] urls = new String[]{
                "/easyban/.*",
                "/common/.*",
                "/user/reg",
                "/user/login",
                "/user/logout",
                "/parentCategories/list",
                "/product/list",
                "/news/page"
        };
        //String[] urls = new String[]{"/.*",};
        boolean check = check(urls, requestURI);
        if (check) {
            log.info("本次请求{}，不需要处理", request.getRequestURI());
            filterChain.doFilter(request, response);
            return;
        }


        //判断登录状态，如果已登录，则直接放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登录，用户id为{}", request.getSession().getAttribute("user"));

            Long id = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(id);

            //判断是否拥有管理员权限
            Integer status = (Integer) request.getSession().getAttribute("status");
            log.info("登录：{}，{}", id, status);

            if (requestURI.contains("/user/getStatus") && status != 0) {
                //如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据。
                response.getWriter().write(JSONUtil.toJsonStr(R.error("NotPower")));
                return;
            }
            if (requestURI.contains("/user/getStatus")) {
                //如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据。
                response.getWriter().write(JSONUtil.toJsonStr(R.error("Login")));
                return;
            }
            filterChain.doFilter(request, response);
            return;
        }

        log.info("用户未登录");
        //如果未登录则返回未登录结果，通过输出流方式向客户端页面响应数据。
        response.getWriter().write(JSONUtil.toJsonStr(R.error("NotLogin")));
        return;
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     *
     * @param urls       允许放行的 URL 数组
     * @param requestURI 请求的 URI
     * @return 如果请求 URI 与任何一个允许放行的 URL 匹配，则返回 true，否则返回 false
     */
    public boolean check(String[] urls, String requestURI) {
        for (String url : urls) {
            if (ReUtil.isMatch(url, requestURI)) return true;
        }
        return false;
    }
}
